package com.wgj.android.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jiaai.xui.XUI;
import com.jiaai.xui.cache.XCache;
import com.jiaai.xui.utils.imageload.XImage;
import com.jiaai.xui.utils.log.XLog;
import com.jiaai.xui.view.widget.XLoadingDialog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.R;
import com.wgj.android.http.WeiXinEvents;
import com.wgj.android.http.weixin.WXFormatUtil;
import com.wgj.android.http.weixin.WXHttp;
import com.wgj.android.http.weixin.WeiXinCacheUtil;
import com.wgj.android.http.weixin.model.AllRequestBody;
import com.wgj.android.http.weixin.model.BaseRequest;
import com.wgj.android.http.weixin.model.WXInfo;
import com.wgj.android.zfp.WXCleanService;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.greenrobot.eventbus.EventBus;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/12/8.
 */

public class WeiXinLoginActivity extends AppCompatActivity {
    @BindView(R.id.qrCode)
    ImageView qrCode;

    @BindView(R.id.login)
    View loginView;

    private String qrUrl;

    public  static void openWeiXingLoginUI(Context context){
        Intent intent=new Intent(context,WeiXinLoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.weixin_login_activity);
        ButterKnife.bind(this);
        getQrCode();

    }



    private void  getQrCode(){
        XLoadingDialog.with(this).setMessage("正在获取二维码").show();
        //获取二维码uuid
        String url = "http://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb".concat(
                "&redirect_uri=https%3A%2F%2Fwx2.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage")
                .concat("&fun=new&lang=zh_CN")
                .concat("]&_=").concat(""+(new Date().getTime() + (1000*60*60*24)));
        WXHttp.obtain().get(url, null, new WXHttp.WXHttpCallback() {
            @Override
            public void onSuccess(String body) {
                final String uuid = body.substring(body.indexOf("= \"") + 3, body.length() - 2);
                XCache.get(XUI.getContext()).put("uuid", uuid);

                qrUrl="https://login.weixin.qq.com/qrcode/".concat(uuid);
                try{
                    WeiXinLoginActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            XImage.getInstance().load(qrCode,qrUrl);
                            XLoadingDialog.with(WeiXinLoginActivity.this).dismiss();
                            loginWX(uuid);
                        }
                    });
                }catch (Exception e){

                }


            }

            @Override
            public void onFailed(boolean isNettWork) {

            }
        });

    }

    //登录微信
    private void loginWX(final String uuid){
        int i = (int) (new Date().getTime() + (1000*60*60*24));
        String loginUrl = "http://login.wx.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true" +
                "&uuid=".concat(uuid) +
                "&tip=0" +
                "&r=".concat("" + (~i)) +
                "&_=".concat(""+i);
        WXHttp.obtain().get(loginUrl, null, new WXHttp.WXHttpCallback() {
            @Override
            public void onSuccess(String body) {
                String uri =body;//todo 完善 400 408
                String code=uri.substring(12,15);
                switch (code){
                    case "201":
                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                loginView.setVisibility(View.VISIBLE);
                                loginWX(uuid);
                            }
                        },200);
                        break;
                    case "200":
                        if (!WXHttp.checkIsLogin()){
                            WXInfo info=new WXInfo();
                            info.setTicket( uri.substring(uri.indexOf("ticket=") + 7, uri.indexOf("&uuid")));
                            info.setScan(uri.substring(uri.indexOf("&scan=") + 6, uri.length() - 2));
                            info.setBaseUrl(uri.substring(uri.indexOf("https")+8,uri.indexOf("com")+3));
                            WeiXinCacheUtil.saveInfo(info);
                            XLog.json(new Gson().toJson(WeiXinCacheUtil.getInfo()));
                            getMyWXInfo();
                        }
                        break;
                    case "400":
                         new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getQrCode();
                                XToast.warning("二维码已失效,请重新扫描");
                                loginView.setVisibility(View.GONE);
                            }
                        },200);

                    case "408":
                        loginWX(uuid);
                        break;
                    default:
                            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    XToast.error("微信登录失败,请确保你的web版微信能够正常登录");
                                    loginView.setVisibility(View.GONE);
                                }
                            },300);
                        break;
                }

            }

            @Override
            public void onFailed(boolean isNettWork) {
                loginWX(uuid);
            }
        });
    }

    /**
     * 获取我的微信信息和cookie
     */
    private void getMyWXInfo(){

        final WXInfo info= WeiXinCacheUtil.getInfo();

        String cookie = WeiXinCacheUtil.getCookie();
        String url = "http://" + info.getBaseUrl()+"/cgi-bin/mmwebwx-bin/webwxnewloginpage?" +
                "fun=new" +
                "&version=v2" +
                "&lang=zh_CN";
        url+="&ticket=".concat(info.getTicket()) +
                "&uuid=".concat(XCache.get(WeiXinLoginActivity.this).getAsString("uuid")) +
                "&scan=".concat(info.getScan());
        try {
            String body= WXHttp.obtain().syncGet(url, null);
            Document document = null;
            try {
                document = DocumentHelper.parseText(body);
                Element root = document.getRootElement();
                List<Element> elements = root.elements();

                for (Iterator<Element> it = elements.iterator(); it.hasNext();) {
                    Element element = it.next();
                    if (element.getName().equals("ret") && !element.getText().equals("0")) {
                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                            XToast.error("微信登录失败,请确保你的web版微信能够正常登录");
                            loginView.setVisibility(View.GONE);
                            }
                        },300);

                    };

                    if (element.getName().equals("skey")) info.setSkey(element.getText());
                    else if (element.getName().equals("wxsid")) info.setWxsid(element.getText());
                    else if (element.getName().equals("wxuin")) info.setWxuin(element.getText());
                    else if (element.getName().equals("pass_ticket")) info.setPass_ticket(element.getText());
                }
                WeiXinCacheUtil.saveInfo(info);
                getSynckeyAndUserName();

            } catch (DocumentException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //获取心跳所需的synckey
    private void getSynckeyAndUserName(){
        final WXInfo info= WeiXinCacheUtil.getInfo();

        if(info != null){
            AllRequestBody allRequestBody = new AllRequestBody();
            BaseRequest baseRequest = new BaseRequest();
            baseRequest.setDeviceID("e" + (WXFormatUtil.getRand15Num()));
            baseRequest.setSid(info.getWxsid());
            baseRequest.setSkey(info.getSkey());
            baseRequest.setUin(Long.parseLong(info.getWxuin()));
            allRequestBody.setBaseRequest(baseRequest);

            String  url = "http://".concat(info.getBaseUrl())+"/cgi-bin/mmwebwx-bin/webwxinit?" +
                    "r=".concat(WXFormatUtil.getNDate()) +
                    "&lang=zh_CN";
            try {
                String body=WXHttp.obtain().syncPost(url,new Gson().toJson(allRequestBody));
                JSONObject ob=JSONObject.parseObject(body);
                info.setSyncKey(ob.getString("SyncKey"));
                info.setUserName(JSONObject.parseObject(ob.getString("User")).get("UserName").toString());
                WeiXinCacheUtil.saveSynckey(ob.getString("SyncKey"));
                info.setLogin(true);
                WeiXinCacheUtil.saveInfo(info);
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new WeiXinEvents(WeiXinEvents.EventsType.LOGIN));

                        XToast.success("登录成功");
                       finish();
                    }
                },300);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}
